import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, ValidationErrors, Validators} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {ListService} from '../../../services/list/list.service';
import {NzModalService} from 'ng-zorro-antd';

@Component({
  selector: 'app-right-control',
  templateUrl: './right-control.component.html',
  styleUrls: ['./right-control.component.less']
})
export class RightControlComponent implements OnInit {

  flag = 'article';
  urlTemp = '/home/save';
  validateForm: FormGroup;


  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    private listService: ListService,
    private modalService: NzModalService) {
    this.validateForm = this.fb.group({
      userName: ['', [Validators.required]],
      email: ['', [Validators.required]],
      password: ['', [Validators.required]],
      confirm: ['', [Validators.required]],
      comment: ['', [Validators.required]],
    });
  }

  ngOnInit() {
    this.listService.eventBus.subscribe((value) => {
      this.flag = value;
      this.urlTemp = value == 'article' ? '/home/save' : '/blog/life/save';
      if (this.flag === 'article') {
        this.validateForm = this.fb.group({
          userName: ['', [Validators.required]],
          email: ['', [Validators.required]],
          password: ['', [Validators.required]],
          confirm: ['', [Validators.required]],
          comment: ['', [Validators.required]],
        });
      } else {
        this.validateForm = this.fb.group({
          userName: ['', [Validators.required]],
          // email: ['', [Validators.required]],
          // password: ['', [Validators.required]],
          confirm: ['', [Validators.required]],
          comment: ['', [Validators.required]],
        });
      }
    });
  }

  submitForm = ($event, value) => {

    this.http.post(`http://localhost:9999${this.urlTemp}`, value).subscribe();
    this.modalService.success({
      nzTitle: '成功',
      nzContent: `${this.flag === 'article' ? '文章' : '日记'}添加成功`
    });
    this.validateForm.reset();
    // tslint:disable-next-line:forin
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[ key ].markAsPristine();
      this.validateForm.controls[ key ].updateValueAndValidity();
    }
  }
}
